package com.java.jvm;

class Outer{
    /**
     * 实例内部类
     */
    class Inner extends Thread{
        @Override
        public void run() {
            while(true){
                try{Thread.sleep(500);}catch (Exception e){}
            }
        }
    }

    /**
     * 静态内部类 (不依赖于外部类对象,不会保存对外部类的引用)
     */
    static class StaticInner extends Thread{
        @Override
        public void run() {
            while(true){
                try{Thread.sleep(500);}catch (Exception e){}
            }
        }
    }

    /**
     * 此方法会在对象回收之前执行，这里重写主要是为监控，方法所在的类的对象是否销毁了
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize()");
    }
}
//-XX:+PrintGC
public class OuterInnerTests {
    static void doInstanceInner(){
        Outer o1=new Outer();
        Outer.Inner inner=o1.new Inner();//实例内部类是先有外部类对象,再有内部类对象.
        inner.start();
        o1=null;
        //手动启动
        System.gc();
    }
    static void doStaticInner(){
        Outer outer=new Outer();
        Outer.StaticInner inner=new Outer.StaticInner();
        inner.start();
        outer=null;
        //手动启动
        System.gc();
    }
    public static void main(String[] args) {
        //1.实例内部类测试
        //doInstanceInner();
        //2.静态内部类测试
        doStaticInner();
    }
}
